package com.zrrd.yunchmall.order.controller;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.yunchmall.order.client.AdminServiceClient;
import com.zrrd.yunchmall.order.client.ProductServiceClient;
import com.zrrd.yunchmall.order.entity.Order;
import com.zrrd.yunchmall.order.entity.OrderItem;
import com.zrrd.yunchmall.order.service.IOrderItemService;
import com.zrrd.yunchmall.order.service.IOrderOperateHistoryService;
import com.zrrd.yunchmall.order.service.impl.OrderServiceImpl;
import com.zrrd.yunchmall.user.entity.Admin;
import com.zrrd.yunchmall.util.JwtUtil;
import com.zrrd.yunchmall.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author YeKong
 * @since 2024-01-15
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/order")
@Api(tags = "订单服务接口")
public class OrderController {

    @Autowired
    private ProductServiceClient productService;
    @Autowired
    private AdminServiceClient adminService;
    @Autowired
    private OrderServiceImpl orderService;
    @Autowired
    private IOrderItemService orderItemService;
    @Autowired
    private IOrderOperateHistoryService orderOperateHistoryService;

    @GetMapping("/{orderId}")
    @ApiOperation("查询订单详情")
    public ResponseResult detail(@PathVariable("orderId") long orderId) {
        Order order = orderService.getById(orderId);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id", orderId);
        //查询订单的列表
        order.setOrderItemList(orderItemService.list(queryWrapper));
        //查询操作历史
        order.setHistoryList(orderOperateHistoryService.list(queryWrapper));
        return new ResponseResult(200, "查询成功", order);
    }

    @ApiOperation("订单发货")
    @PostMapping("/update/delivery")
    public ResponseResult updateDelivery(@RequestBody List<Map<String, Object>> params) {
        orderService.delivery(params);
        return new ResponseResult(200, "发货成功");
    }

    @ApiOperation("关闭订单")
    @PostMapping("/update/close")
    public ResponseResult updateClose(@RequestParam String ids,
                                      @RequestParam(defaultValue = "无理由") String note) {
        orderService.closeOrder(ids, note);
        return new ResponseResult(200, "关闭成功");
    }

    @GetMapping("/testSleuth")
    @ApiOperation("测试链路追踪")
    public String testSleuth() {
        //模拟分别调用商品和用户服务
        adminService.testSleuth();
        productService.testSleuth();
        return "测试链路追踪";
    }

    @ApiOperation("查找所有的订单")
    @GetMapping("/list")
    public ResponseResult list(@RequestParam int pageNum, @RequestParam int pageSize,
                               @RequestParam(required = false) String orderSn,
                               @RequestParam(required = false) String receiverKeyword,
                               @RequestParam(required = false) Integer status,
                               @RequestParam(required = false) Integer orderType,
                               @RequestParam(required = false) Integer sourceType,
                               @RequestParam(required = false) String createTime) {
        QueryWrapper queryWrapper = new QueryWrapper();
        //过滤掉已删除的订单
        queryWrapper.ne("delete_status", 1);
        if (!StringUtils.isEmpty(orderSn)) {
            queryWrapper.eq("order_sn", orderSn);
            //在查询语句的末尾拼接一个limit 1， 提高查询效率
            queryWrapper.last("limit 1");//限制查询条数，当查到一条时数据库停止查询并返回数据
            List<Order> orderList = orderService.list(queryWrapper);
            IPage page = new Page(pageNum, pageSize);
            page.setTotal(orderList.size());
            page.setPages(orderList.size());
            page.setRecords(orderList);
            return new ResponseResult(200, "查询成功", page);
        }else  {
            if (!StringUtils.isEmpty(receiverKeyword)) {
                String regStr = "^1[3456789]\\d{9}";
                //正则表达式的 API Pattern 和 Matcher
                Pattern pattern = Pattern.compile(regStr);//编译正则表达式
                Matcher matcher = pattern.matcher(receiverKeyword);//使用正则的规则去匹配给定的字符串

                //matcher.find 部分匹配
                //matcher.matches 完全匹配
                if (matcher.matches()) {
                    queryWrapper.eq("receiver_phone", receiverKeyword);
                }else {
                    queryWrapper.eq("receiver_name", receiverKeyword);
                }
            }
            if (!StringUtils.isEmpty(status))
                queryWrapper.eq("status", status);
            if (!StringUtils.isEmpty(orderType))
                queryWrapper.eq("order_type", orderType);
            if (!StringUtils.isEmpty(sourceType))
                queryWrapper.eq("source_type", sourceType);
            if (!StringUtils.isEmpty(createTime)) {
                String start = createTime + " 00:00:00";
                String end = createTime + " 23:59:59";
                queryWrapper.between("create_time", start, end);
            }
        }
        return new ResponseResult(200, "查找成功",
                orderService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @ApiOperation("删除订单")
    @PostMapping("/delete")
    public ResponseResult updateDelete(@RequestParam String ids,
                                       @RequestHeader("Authorization") String token) {
        //从token中获得当前操作的管理员信息
        Admin admin = JwtUtil.parseAdminToken(token.substring(7));
        orderService.remove(ids, admin);
        return new ResponseResult(200, "删除成功");
    }

    @ApiOperation("修改收货人的信息")
    @PostMapping("/update/receiverInfo")
    public ResponseResult updateReceiverInfo(@RequestBody Map<String, Object> params){
        orderService.updateReceiverInfo(params);
        return new ResponseResult(200, "修改成功");
    }

    @ApiOperation("费用")
    @PostMapping("/update/moneyInfo")
    public ResponseResult updateMoneyInfo(@RequestBody Map<String, Object> params,
                                          @RequestHeader("Authorization") String token) {
        Admin admin = JwtUtil.parseAdminToken(token.substring(7));
        orderService.updateMoneyInfo(params, admin);
        return new ResponseResult(200, "修改成功");
    }

}
